#!/usr/bin/env python3
"""
简单的数据引擎启动脚本
只启动数据采集引擎，不启动Web服务
"""

import sys
import os
import logging
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

# 设置简单的日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[logging.StreamHandler()]
)

def main():
    print("🚀 启动数据采集引擎（仅数据引擎模式）")
    print("=" * 50)
    
    try:
        # 1. 检查依赖
        print("📦 检查依赖...")
        try:
            from core.engine import DataEngine
            from services.storage import StorageService
            from services.alarm import AlarmService
            from services.config_manager import ConfigManager
            print("✅ 核心模块导入成功")
        except ImportError as e:
            print(f"❌ 模块导入失败: {e}")
            return False
        
        # 2. 创建必要目录
        os.makedirs('logs', exist_ok=True)
        os.makedirs('data', exist_ok=True)
        print("✅ 目录创建完成")
        
        # 3. 初始化存储服务
        print("🗃️  初始化存储服务...")
        storage_service = StorageService({'database': 'data/iot_collector.db'})
        
        # 4. 初始化报警服务
        print("🚨 初始化报警服务...")
        alarm_service = AlarmService({})
        
        # 5. 创建数据引擎
        print("⚙️  创建数据采集引擎...")
        engine = DataEngine(
            storage_service=storage_service,
            alarm_service=alarm_service,
            max_workers=4
        )
        
        # 6. 加载设备配置
        print("📋 加载设备配置...")
        config_manager = ConfigManager()
        devices_config = config_manager.load_devices()
        
        print(f"发现 {len(devices_config)} 个设备配置")
        
        device_loaded = 0
        for device_config in devices_config:
            try:
                device_name = device_config.get('name')
                driver_type = device_config.get('type')
                enabled = device_config.get('enabled', True)
                
                print(f"\n📄 处理设备: {device_name} ({driver_type})")
                
                if not device_name or not driver_type:
                    print(f"  ⚠️  配置缺少名称或类型，跳过")
                    continue
                
                if not enabled:
                    print(f"  💤 设备被禁用，跳过")
                    continue
                
                # 创建设备驱动
                driver = create_device_driver(driver_type, device_config)
                if driver:
                    engine.add_device(device_name, driver)
                    device_loaded += 1
                    print(f"  ✅ 设备驱动创建成功")
                else:
                    print(f"  ❌ 设备驱动创建失败")
                
            except Exception as e:
                print(f"  ❌ 设备加载异常: {e}")
        
        print(f"\n📊 设备加载统计: {device_loaded}/{len(devices_config)} 成功")
        
        # 7. 启动数据引擎
        print("\n🚀 启动数据采集引擎...")
        engine.start()
        
        print("✅ 数据引擎启动成功！")
        print("\n📋 引擎状态:")
        print(f"  - 已加载设备数: {len(engine.devices)}")
        print(f"  - 引擎运行状态: {engine.running}")
        
        # 8. 测试设备连接
        print("\n🔍 测试设备连接...")
        for device_name, driver in engine.devices.items():
            try:
                if driver.connect():
                    print(f"  ✅ {device_name}: 连接成功")
                    
                    # 尝试读取数据
                    data_points = list(driver.data_points.keys())
                    if data_points:
                        tag_values = driver.read_tags(data_points[:3])  # 读取前3个数据点
                        print(f"    📊 读取到 {len(tag_values)} 个数据点:")
                        for tag_value in tag_values:
                            print(f"      - {tag_value.tag_name}: {tag_value.value} ({tag_value.quality})")
                    else:
                        print(f"    ⚠️  没有配置数据点")
                else:
                    print(f"  ❌ {device_name}: 连接失败")
                    
            except Exception as e:
                print(f"  ❌ {device_name}: 连接异常 - {e}")
        
        # 9. 保持运行
        print("\n⏳ 数据引擎运行中...")
        print("按 Ctrl+C 停止引擎")
        
        try:
            while True:
                import time
                time.sleep(5)
                
                # 显示引擎状态和最新数据
                latest_data = engine.get_all_latest_data()
                print(f"📊 引擎状态 - 设备数: {len(engine.devices)}, 运行: {engine.running}")
                
                # 显示每个设备的最新数据
                for device_name, device_data in latest_data.items():
                    if device_data:
                        print(f"  📡 {device_name}:")
                        for tag_name, tag_value in device_data.items():
                            if hasattr(tag_value, 'value'):
                                print(f"    - {tag_name}: {tag_value.value} ({tag_value.quality}) @ {tag_value.timestamp}")
                            else:
                                print(f"    - {tag_name}: {tag_value}")
                    else:
                        print(f"  📡 {device_name}: 暂无数据")
                
        except KeyboardInterrupt:
            print("\n🛑 收到停止信号，正在关闭...")
            engine.stop()
            print("✅ 数据引擎已停止")
            
        return True
        
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def create_device_driver(driver_type: str, device_config: dict):
    """创建设备驱动实例"""
    try:
        if driver_type == 'modbus':
            from core.drivers.modbus import ModbusDriver
            return ModbusDriver(device_config)
        elif driver_type == 's7':
            from core.drivers.s7 import S7Driver
            return S7Driver(device_config)
        elif driver_type == 'opcua':
            from core.drivers.opcua import OpcuaDriver
            return OpcuaDriver(device_config)
        elif driver_type == 'mqtt':
            from core.drivers.mqtt import MqttDriver
            return MqttDriver(device_config)
        else:
            print(f"❌ 不支持的设备类型: {driver_type}")
            return None
            
    except ImportError as e:
        print(f"❌ 导入驱动模块失败: {e}")
        return None
    except Exception as e:
        print(f"❌ 创建驱动实例失败: {e}")
        return None

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1) 